package cn.xuqiudong.sso.client.session.shiro;

import cn.xuqiudong.sso.client.session.SessionMappingStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpSession;

/**
 * 描述:
 *      如果客户端通过shiro实现session共享的话
 * @author Vic.xu
 * @since 2021-11-09 17:38
 */
public class ShiroRedisSessionMappingStorage implements SessionMappingStorage {

    private static final String TOKEN_SESSION_KEY = "token_session_key_";

    private static final String SESSION_TOKEN_KEY = "session_token_key_";
    /**
     * shiro在redis中保存session的map的cacheName
     */
    private static String shiroSessionCacheName = "shiro-activeSessionCache";

    public void setShiroSessionCacheName(String shiroSessionCacheName) {
        ShiroRedisSessionMappingStorage.shiroSessionCacheName = shiroSessionCacheName;
    }

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public synchronized HttpSession removeSessionByMappingId(String accessToken) {
        final String sessionId = (String) redisTemplate.opsForValue().get(TOKEN_SESSION_KEY + accessToken);
        if (sessionId != null) {
            removeBySessionById(sessionId);
        }
        return null;
    }

    @Override
    public synchronized void removeBySessionById(String sessionId) {

        final String accessToken = (String) redisTemplate.opsForValue().get(SESSION_TOKEN_KEY + sessionId);
        if (accessToken != null) {
            redisTemplate.delete(TOKEN_SESSION_KEY + accessToken);
            redisTemplate.delete(SESSION_TOKEN_KEY + sessionId);
        }
        //删除redis中的session
        redisTemplate.opsForHash().delete(shiroSessionCacheName, sessionId);

    }

    @Override
    public synchronized void addSessionById(String accessToken, HttpSession session) {
        redisTemplate.opsForValue().set(SESSION_TOKEN_KEY + session.getId(), accessToken);

        redisTemplate.opsForValue().set(TOKEN_SESSION_KEY + accessToken, session.getId());
    }
}
